<!--
@description:
@author: ldb
@time: 2022-11-24 13:52:46
-->
<template>
  <a-form
    ref="baseForm"
    :model="formState"
    :label-col="{ span: 3 }"
    :wrapper-col="{ span: 24 }"
    autocomplete="off"
    @finish="form.onFinish(beforeSubmit)"
    @finishFailed="form.onFinishFailed"
  >
    <base-form-item v-for="item in formItems" :key="item.name" v-model:value="formState[item.name]" v-bind="item" />
    <a-form-item v-show="type !== 1" :wrapper-col="{ span: 24, offset: 10 }">
      <a-button type="primary" html-type="submit">确认</a-button>
      <a-button style="margin-left: 10px" @click="form.cancel">取消</a-button>
    </a-form-item>
  </a-form>
</template>

<script lang="ts" setup>
import { defineProps, reactive, onMounted } from 'vue'
import { user, UserRole } from '@/entity/system/user'
import { useForm } from '@/hooks/base/FormHooks'
import { USER_API_PRE_SUFFER } from '@/api/system/user'
import { formItems } from '@/views/sys/user/forms'
import { injectCustomUpdateOptions } from '@/utils/form-item-util'
import { deptSelected } from '@/api/system/dept'
import { roleSelected } from '@/api/system/role'
const props = defineProps<{ id: string; type: number }>()
const formState = reactive<Partial<user>>({})
const form = useForm(USER_API_PRE_SUFFER, formState, props, formItems)
onMounted(async () => {
  await form.init(() => {
    formState.userRole = formState?.userRoles?.map((val) => val.id) as Array<string>
  })
  await injectCustomUpdateOptions(formItems.value, 'deptId', deptSelected)
  await injectCustomUpdateOptions(formItems.value, 'userRole', roleSelected)
})

/**
 * 提交之前
 */
function beforeSubmit() {
  if (formState.userRole) {
    formState.userRole = formState.userRole.map((val) => {
      return {
        roleId: val,
      } as UserRole
    })
  }
}
</script>

<style scoped lang="scss"></style>
